<template>
	<view class="main" @click.stop>
		<view v-if="isRecording" class="overlay" :style="{ width: windowWidth, height: windowHeight }">
			<view class="infomation">
				<view class="info">
					<text style="font-size: 50rpx; font-weight: 500; color: white">{{ isMovingToLeft ? '录音取消' : '录音中...' }}</text>
				</view>

				<view class="times">
					<text style="font-size: 50rpx; color: white">{{ times }}</text>
				</view>
			</view>

			<view v-if="isRecording" class="left-button" :class="{ cancel: isMovingToLeft }">
				<text>取消</text>
			</view>
			<view class="btn"></view>
		</view>

		<view :class="['speeker', customClass]" :style="customStyle" @touchmove.stop="handleTouchMove" @touchstart.stop="startRecording" @touchend.stop="stopRecording">
			<text :style="styleTxT">按住说话</text>
		</view>
	</view>
</template>

<script>
import checkPermissions from '../utils/checkPermissions';

export default {
	name: 'recordVioce',
	props: {
		customClass: {
			type: String,
			default: ''
		},
		customStyle: {
			type: Object,
			default: () => ({})
		},
		styleTxT: {
			type: Object,
			default: () => ({})
		}
	},

	data() {
		return {
			timerId: null,
			isMovingToLeft: false,
			voicePath: '',
			recorderManager: uni.getRecorderManager(),
			innerAudioContext: uni.createInnerAudioContext(),
			duration: 0,
			voiceData: null,
			audioContext: null,
			count: 0,
			isRecording: false,
			times: 60,
			iscancel: false,
			startX: 0,
			startY: 0,
			windowHeight: 0,
			windowWidth: 0
		};
	},
	created() {
		const _this = this;
		this.audioContext = uni.createInnerAudioContext();
		this.innerAudioContext.autoplay = true; // 注意：部分平台可能仍需要用户交互

		this.windowHeight = this.$store.state.msg.systemInfo.windowHeight;
	},
	mounted() {
		// 统一初始化事件监听
       	const hasPermission = checkPermissions('record', '麦克风');
		const res = this.$store.state.msg.systemInfo;
		this.windowHeight = res.windowHeight;
		this.windowWidth = res.windowWidth;

		this.recorderManager.onStop(async (res) => {
			if (this.iscancel) {
				this.stoptimer();
				uni.showToast({
					icon: 'fail',
					title: '录音取消发送',
					position: 'center'
				});
				return;
			}

			this.voicePath = res.tempFilePath;
			try {
				this.audioContext.src = this.voicePath;
				// 监听音频元数据加载完成事件
				this.audioContext.onCanplay(async () => {
					this.duration = await this.audioContext.duration;
					if (this.duration < 1) {
						uni.showToast({
							icon: 'fail',
							title: '录音太短,已取消！',
							duration: 2000,
							position: 'center'
						});
						return;
					}
					this.count++;
					this.voiceData = await this.uploadVoice(this.voicePath);
					this.$emit('voiceMsg', this.voiceData);
				});

				//this.playVoice();
			} catch (error) {
				console.error('上传语音文件出错:', error);
			}
		});
		this.recorderManager.onError((err) => {
			this.stoptimer();
			this.isRecording = false;
			console.error(' 录音出错:', err);
		});
	},

	methods: {
		handleClose(e) {
			e.stopPropagation();

			this.$emit('handleclose');
		},
		async startRecording(event) {
		
	    	uni.vibrateShort();
			this.isRecording = true;
			this.isMovingToLeft = false;
			const touch = event.changedTouches[0];
			this.startX = touch.pageX;
			this.startY = touch.pageY;
			this.timer();
			this.recorderManager.start({
				format: 'mp3', // 录音格式，可根据需求选择
				sampleRate: 44100,
				duration: 60000 // 最长录音时间（根据需要调整）
			});
			console.log(' 开始录音...');
		},
		handleTouchMove(event) {
			if (!this.isRecording) return;
			const touch = event.changedTouches[0];
			const moveX = touch.pageX;
			const moveY = touch.pageY;
			const dx = moveX - this.startX;
			const dy = moveY - this.startY;

			// 这里简单判断向左移动一定距离认为是移动到左边按钮取消
			if (dx < -45 && dy < -45) {
				this.iscancel = true;
				this.isMovingToLeft = true;
			} else {
				this.iscancel = false;
				this.isMovingToLeft = false;
			}
		},
		stopRecording() {
			this.stoptimer();
			this.isRecording = false;
			this.recorderManager.stop();

			console.log(' 停止录音，路径即将更新');
		},
		playVoice() {
			console.log('录后播放。。。。');
			if (this.voicePath) {
				this.innerAudioContext.src = this.voicePath;
				this.innerAudioContext.play();
			}
		},
		timer() {
			this.timerId = setInterval(() => {
				if (this.times > 0) {
					this.times--; // 时间减 1
				} else {
					// 时间减到 0，停止定时器
					this.stoptimer();
				}
			}, 1000);
		},
		stoptimer() {
			if (this.timerId) {
				clearInterval(this.timerId);
				this.timerId = null;
				this.times = 60;
			}
		},

		async uploadVoice(path) {
			try {
				// 生成一个唯一的文件名
				const uniqueId = Date.now();
				// 上传文件到 uniCloud 云存储
				const uploadRes = await uniCloud.uploadFile({
					cloudPath: `voice/${uniqueId}.mp3`,
					filePath: path
				});

				// 获取文件的临时访问 URL
				const urlRes = await uniCloud.getTempFileURL({
					fileList: [uploadRes.fileID]
				});

				return {
					voicePath: urlRes.fileList[0].tempFileURL,
					fileId: urlRes.fileList[0].fileID,
					duration: this.duration
				};
			} catch (error) {
				// 错误处理

				return null;
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.overlay {
	position: fixed;
	flex-direction: column;
	display: flex;
	buttom: 0;
	left: 0;
	right: 0;
	top: 0;

	background: linear-gradient(to top, rgba(0, 0, 0, 6), rgba(0, 0, 0, 0.1));
	z-index: 500;
}
.infomation {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding-bottom: 100rpx;
	align-self: center;
	justify-self: center;
	margin-top: 600rpx;
	margin-bottom: 200rpx;
}

.info {
	color: white;
	font-size: 50rpx;
	font-weight: 500;
	color: white;
	margin-bottom: 50rpx;
	justify-self: center;
	align-self: center;
}

.times {
	color: white;
	font-size: 100rpx;
	font-weight: 500;
}

.speeker {
	display: flex;
	width: 100%;
	height: 100%;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	padding: 10rpx;
}

.active {
	background-color: #f0ff67;
}

.left-button {
	display: flex;
	background-color: #007aff;
	width: 200rpx;
	margin-left: 50rpx;
	align-items: center;
	justify-content: center;
	height: 200rpx;
	font-size: 50rpx;
	margin-bottom: 250rpx;
	font-weight: 600;
	color: white;
	border-radius: 100rpx;
	cursor: pointer;
}

.voicebox {
	display: flex;
	width: 100%;
	height: 100%;
	align-items: center;
	justify-content: center;
	pointer-events: auto;
}
.closeicon {
	position: absolute;
	right: 30rpx;
	bottom: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	width: 60rpx;
	height: 60rpx;
	border-radius: 30rpx;
	background-color: white;
	border: 1rpx solid #007aff;
}

.cancel {
	background-color: red;
}
</style>
